import * as vscode from 'vscode'
import { createWebViewDebugger } from '../../utils/debugLogger'
import { generateFormHtml } from './templates/formTemplate'
import { FormConfig, FormContext } from './types'
import { validateFormConfig } from './utils/configValidator'
import { formLogger } from './utils/logger'

// 重新导出类型以保持向后兼容
export { FormField, FormConfig, FormContext } from './types'

// 全局面板管理
const activePanels = new Map<string, vscode.WebviewPanel>()

export async function showGenericForm(config: FormConfig): Promise<any> {
  return new Promise((resolve, reject) => {
    try {
      formLogger.info('开始显示表单', { viewType: config.viewType })

      // 验证配置
      const validation = validateFormConfig(config)
      if (!validation.isValid) {
        const errorMsg = '表单配置无效: ' + validation.errors.join(', ')
        formLogger.error(errorMsg, validation.errors)
        reject(new Error(errorMsg))
        return
      }

      // 使用验证后的配置
      const safeConfig = validation.sanitizedConfig

      // 创建面板
      const panel = vscode.window.createWebviewPanel(safeConfig.viewType, safeConfig.panelTitle || safeConfig.title, vscode.ViewColumn.One, {
        enableScripts: true,
        retainContextWhenHidden: true,
        localResourceRoots: []
      })

      // 生成调试信息
      const debugHtml = createDebugInfo(safeConfig)
      const debugStyles = createDebugStyles()
      const debugScript = createDebugScript(safeConfig)

      // 设置网页内容
      try {
        panel.webview.html = generateFormHtml(safeConfig, debugHtml, debugStyles, debugScript)
        formLogger.info('表单HTML生成成功')
      } catch (error) {
        formLogger.error('生成表单HTML失败', error)
        panel.dispose()
        reject(error)
        return
      }

      // 消息处理
      const disposable = panel.webview.onDidReceiveMessage(message => {
        try {
          formLogger.info('收到表单消息', { command: message.command })

          switch (message.command) {
            case 'submit':
              formLogger.info('表单提交', { data: message.data })
              resolve(message.data)
              disposable.dispose()
              panel.dispose()
              break
            case 'cancel':
              formLogger.info('表单取消')
              resolve(null)
              disposable.dispose()
              panel.dispose()
              break
            default:
              formLogger.warn('未知的表单命令', message)
          }
        } catch (error) {
          formLogger.error('处理表单消息失败', error)
          reject(error)
          disposable.dispose()
          panel.dispose()
        }
      }, undefined)

      // 面板关闭处理
      panel.onDidDispose(() => {
        try {
          formLogger.info('表单面板关闭')
          disposable.dispose()
          resolve(null)
        } catch (error) {
          formLogger.error('面板关闭处理失败', error)
        }
      })
    } catch (error) {
      formLogger.error('显示表单失败', error)
      reject(error)
    }
  })
}

function createDebugInfo(config: FormConfig): string {
  return `
    <div id="debugInfo" style="background: var(--vscode-textBlockQuote-background); padding: 10px; margin-bottom: 15px; border-radius: 4px; font-size: 12px;">
      <div>🔧 调试信息</div>
      <div>表单类型: ${config.viewType}</div>
      <div>字段数量: ${config.fields.length}</div>
      <div>时间戳: ${new Date().toLocaleString()}</div>
    </div>
  `
}

function createDebugStyles(): string {
  return `
    #debugInfo {
      border-left: 3px solid var(--vscode-textLink-foreground);
    }
  `
}

function createDebugScript(config: FormConfig): string {
  return `
    // 调试日志函数
    function log(message) {
      console.log('[表单调试] ' + new Date().toLocaleTimeString() + ' - ' + message);
      
      // 更新调试信息显示
      const debugInfo = document.getElementById('debugInfo');
      if (debugInfo) {
        const logDiv = document.createElement('div');
        logDiv.textContent = new Date().toLocaleTimeString() + ' - ' + message;
        logDiv.style.fontSize = '11px';
        logDiv.style.color = 'var(--vscode-descriptionForeground)';
        debugInfo.appendChild(logDiv);
        
        // 限制日志显示数量
        const logs = debugInfo.querySelectorAll('div:not(:first-child)');
        if (logs.length > 10) {
          logs[0].remove();
        }
      }
    }
    
    // 页面加载完成日志
    log('${config.debugMessage || '表单页面加载完成'}');
  `
}
